<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>人脸识别与注册测试</title>
        <style>
            body {
                font-family: Arial, sans-serif;
            }
            #videoElement {
                width: 640px;
                height: 480px;
                border: 1px solid #ddd;
            }
            .btn {
                padding: 10px 20px;
                margin-top: 10px;
                cursor: pointer;
                background-color: #4caf50;
                color: white;
                border: none;
                border-radius: 5px;
            }
            .btn:hover {
                background-color: #45a049;
            }
            .message {
                margin-top: 10px;
            }
        </style>
    </head>
    <body>
        <h1>人脸识别与注册测试</h1>

        <!-- 用户注册 -->
        <h2>用户注册</h2>
        <form id="registerForm">
            <input
                type="text"
                id="userId"
                placeholder="请输入用户 ID"
                required
            />
            <input type="file" id="registerFile" accept="image/*" required />
            <button type="submit" class="btn">注册人脸</button>
        </form>
        <div id="registerMessage" class="message"></div>

        <!-- 人脸识别 -->
        <h2>实时人脸识别</h2>
        <video id="videoElement" autoplay></video>
        <button id="startRecognition" class="btn">开始实时人脸识别</button>
        <div id="recognizeMessage" class="message"></div>

        <script>
            // 处理视频流和 WebSocket
            let video = document.getElementById("videoElement");
            let startButton = document.getElementById("startRecognition");
            let registerForm = document.getElementById("registerForm");
            let userIdInput = document.getElementById("userId");
            let registerFileInput = document.getElementById("registerFile");
            let registerMessage = document.getElementById("registerMessage");
            let recognizeMessage = document.getElementById("recognizeMessage");
            let socket;

            // 获取视频流并展示在 <video> 元素中
            async function startVideoStream() {
                try {
                    const stream = await navigator.mediaDevices.getUserMedia({
                        video: true,
                    });
                    video.srcObject = stream;
                } catch (err) {
                    console.error("无法访问摄像头:", err);
                    alert("无法访问摄像头，请检查设备或浏览器权限设置。");
                }
            }

            // 处理人脸注册
            registerForm.addEventListener("submit", function (event) {
                event.preventDefault(); // 阻止表单默认提交行为
                let userId = userIdInput.value.trim();
                let file = registerFileInput.files[0];

                if (!userId || !file) {
                    registerMessage.innerText =
                        "请填写完整的用户 ID 和上传图片文件。";
                    return;
                }

                let formData = new FormData();
                formData.append("user_id", userId);
                formData.append("file", file);

                fetch("/register/", {
                    method: "POST",
                    body: formData,
                })
                    .then((response) => response.json())
                    .then((data) => {
                        registerMessage.innerText =
                            data.message || "注册成功！";
                    })
                    .catch((error) => {
                        registerMessage.innerText = `注册失败: ${error}`;
                    });
            });

            // 启动 WebSocket 连接
            function startWebSocket() {
                socket = new WebSocket("ws://127.0.0.1:8000/ws/recognize");

                socket.onopen = () => {
                    console.log("WebSocket 连接已建立！");
                    startButton.disabled = false;
                };

                socket.onmessage = (event) => {
                    let message = JSON.parse(event.data);
                    if (message.faces && message.faces.length > 0) {
                        recognizeMessage.innerText = `检测到 ${message.faces.length} 个面部。`;
                    } else {
                        recognizeMessage.innerText = "没有检测到人脸。";
                    }
                };

                socket.onerror = (error) => {
                    console.error("WebSocket 错误:", error);
                    recognizeMessage.innerText = "WebSocket 错误，请稍后重试。";
                };

                socket.onclose = () => {
                    console.log("WebSocket 连接关闭。");
                    recognizeMessage.innerText = "WebSocket 连接已关闭。";
                };
            }

            // 开始实时人脸识别
            startButton.addEventListener("click", () => {
                if (!socket || socket.readyState !== WebSocket.OPEN) {
                    startWebSocket();
                }

                const canvas = document.createElement("canvas");
                canvas.width = video.videoWidth; // 使用视频的实际宽度
                canvas.height = video.videoHeight; // 使用视频的实际高度
                const context = canvas.getContext("2d");

                // 启动视频流并发送图像帧
                setInterval(() => {
                    context.drawImage(video, 0, 0, canvas.width, canvas.height);
                    let imageData = canvas.toDataURL("image/jpeg");

                    // 发送图像数据到后端进行人脸识别
                    socket.send(imageData.split(",")[1]); // 发送base64编码的图片数据
                }, 300); // 每100ms发送一次图像帧
            });

            // 启动摄像头流
            startVideoStream();
        </script>
    </body>
</html>
